package com.liangsui.cmall.member.service.impl;

import com.liangsui.cmall.member.dao.MemberLevelDao;
import com.liangsui.cmall.member.entity.MemberLevelEntity;
import com.liangsui.cmall.member.exception.MobileExistException;
import com.liangsui.cmall.member.exception.UsernameExistException;
import com.liangsui.cmall.member.vo.MemberLoginVo;
import com.liangsui.cmall.member.vo.MemberOAuth2LoginAndRegisterVo;
import com.liangsui.cmall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liangsui.common.utils.PageUtils;
import com.liangsui.common.utils.Query;

import com.liangsui.cmall.member.dao.MemberDao;
import com.liangsui.cmall.member.entity.MemberEntity;
import com.liangsui.cmall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());

        //检查手机和用户名是否唯一。让controller感知异常，异常机制
        checkMobileUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        //设置手机号
        entity.setMobile(vo.getPhone());
        //设置用户名
        entity.setUsername(vo.getUsername());

        entity.setNickname(vo.getUsername());

        //密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);

        //其他默认信息
        entity.setCreateTime(new Date());

        this.baseMapper.insert(entity);
    }

    @Override
    public void checkMobileUnique(String mobile) throws MobileExistException {
        Long count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", mobile));
        if (count > 0) {
            throw new MobileExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Long count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        //去数据库查询
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if (entity == null) {
            //登录失败
            return null;
        } else {
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity oauthLoginAndRegister(MemberOAuth2LoginAndRegisterVo vo) {
        String giteeId = vo.getGiteeId();
        //判断当前社交用户是否注册过 10823538
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("gitee_id", giteeId));

        if (memberEntity != null) {
            if (!memberEntity.getGiteeName().equals(vo.getGiteeName()) || !memberEntity.getGiteeLogin().equals(vo.getGiteeLogin())) {
                MemberEntity entity = new MemberEntity();
                entity.setGiteeId(giteeId);
                entity.setGiteeLogin(vo.getGiteeLogin());
                entity.setGiteeName(vo.getGiteeName());
                this.baseMapper.update(entity, new QueryWrapper<MemberEntity>().eq("gitee_id", giteeId));
            }
            return memberEntity;
        } else {
            MemberEntity entity = new MemberEntity();
            MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
            entity.setLevelId(levelEntity.getId());
            entity.setGiteeId(giteeId);
            entity.setGiteeLogin(vo.getGiteeLogin());
            entity.setGiteeName(vo.getGiteeName());
            entity.setNickname(vo.getGiteeName());
            entity.setCreateTime(new Date());
            this.baseMapper.insert(entity);
            return null;
        }
    }
}